﻿using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;

namespace FileStorage.Provider.Internal
{
    internal class FileSystemProvider: IStorageProvider
    {
        private readonly FileSystemProviderOptions _options;

        public FileSystemProvider(IOptionsMonitor<FileSystemProviderOptions> optionsMonitor)
        {
            _options = optionsMonitor.CurrentValue;
        }

        public async ValueTask<string> SaveAsync(Stream input, FileMetadata metadata, CancellationToken cancellation)
        {
            throw new System.NotImplementedException();
        }

        public async ValueTask<FileMetadata> GetMetadata(string uri, CancellationToken cancellation)
        {
            throw new System.NotImplementedException();
        }

        public async ValueTask<Stream> OpenReadAsync(string uri, CancellationToken cancellation)
        {
            throw new System.NotImplementedException();
        }

        public async ValueTask DeleteAsync(string uri, CancellationToken cancellation)
        {
            throw new System.NotImplementedException();
        }

        private string CreateUniqueFilePath(string ext)
        {
            var now = DateTime.Now;
            var path = Path.Combine(_options.Path, now.Year.ToString(), now.Month.ToString(), now.Day.ToString());
            Directory.CreateDirectory(path);
            var fileName = now.ToString("HHmmssfff");
            var file = Path.Combine(path, fileName + ext);
            lock (this)
            {
                if (!File.Exists(file)) return file;

                var index = 1;
                while (true)
                {
                    file = Path.Combine(path, $"{fileName}-{index}{ext}");
                    if (!File.Exists(file)) return file;
                    index++;
                }
            }
        }
    }
}